How to add Line breaks to a Textarea in JavaScript 您所在的位置:网站首页 append text to copied content How to add Line breaks to a Textarea in JavaScript

How to add Line breaks to a Textarea in JavaScript

2023-08-05 10:00| 来源: 网络整理| 查看: 265

# Add Line breaks to a Textarea using JavaScript

To add line breaks to a textarea, use the addition (+) operator and add the \r\n string at the place where you want to add a line break.

The combination of the \r and \n characters is used as a newline character.

Here is the HTML for the examples.

index.htmlCopied!doctype html> Your message:

And here is the related JavaScript code.

index.jsCopied!const message = document.getElementById('message'); message.value = 'line one' + '\r\n' + 'line two' + '\r\n' + 'line three'; /** * line one * line two * line three */ console.log(message.value);

If I open my browser, I can see that line breaks have been added at the places where I used the \r\n characters.

The \r character moves the cursor to the beginning of the line but doesn't move it to the next line.

The \n character moves the cursor down to the next line but doesn't return it to the beginning of the line.

The combination of the \r\n characters:

moves the cursor to the beginning of the lineadvances the cursor down to the next lineYou'll see that line breaks are preserved if you console.log the value of your textarea.# Add Line breaks to a Textarea using template literals

You can also use template literals to achieve the same result.

index.jsCopied!const message = document.getElementById('message'); const first = 'line one'; const second = 'line two'; const third = 'line three'; message.value = `${first}\r\n${second}\r\n${third}`;

We used template literals in the example.

The string is wrapped in backticks, not in single quotes.

The dollar sign curly braces syntax allows us to evaluate an expression directly in the template string.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

How to Remove all Line Breaks from a String in JavaScriptAppend text to Textarea using JavaScriptClear the Value of a Textarea using JavaScriptHow to change the href of an anchor tag using JavaScriptDisable text selection on Double-click in CSS or JavaScript


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有